package com.dennytech.tac.ui.activity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.TextView;
import android.widget.Toast;

import com.actionbarsherlock.view.ActionMode;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.dennytech.tac.R;
import com.dennytech.tac.base.CFActivity;
import com.dennytech.tac.model.Attraction;
import com.dennytech.tac.model.Togo;
import com.dennytech.tac.net.api.AttractionListApi;
import com.dennytech.tac.statistics.Stat;
import com.dennytech.tac.ui.adapter.BasicLoadAdapter;
import com.dennytech.tac.ui.adapter.MyPagerAdapter;
import com.dennytech.tac.utils.db.TogoDBHelper;
import com.dennytech.tac.widget.AttractionListItem;

public class MyCollectActivity extends CFActivity implements
		OnItemClickListener, OnItemLongClickListener {

	private static final String LOG_TAG = MyCollectActivity.class.getSimpleName();
	private static final String ACTION_TOGOLIST_CHANGED = "com.dennytech.tac.action.TOGOLIST_CHANGED";

	private ViewPager mPager;
	private List<View> listViews;
	private ImageView cursor;
	private RadioGroup group;
	private int offset = 0;
	private int currIndex = 0;
	private int bmpW;

	private ActionMode mMode;
	private int currentLongClickItem = -1;

	private ListView list1, list2;
	private TodoAttractionListAdapter adapter1, adapter2;

	private BroadcastReceiver receiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {
			Log.i(LOG_TAG,
					"receive broadcast with action: " + intent.getAction());
			if (ACTION_TOGOLIST_CHANGED.equals(intent.getAction())) {
				refresh();
			}
		}
	};

	@Override
	protected void initView() {
		setContentView(R.layout.layout_mycollect);

		group = (RadioGroup) findViewById(R.id.group);
		group.setOnCheckedChangeListener(new OnCheckedChangeListener() {

			@Override
			public void onCheckedChanged(RadioGroup group, int checkedId) {
				if (checkedId == R.id.btn_sort1) {
					mPager.setCurrentItem(0);
					Stat.event("mytrip", "mytrip_check_change", "1", 0);
				} else if (checkedId == R.id.btn_sort2) {
					mPager.setCurrentItem(1);
					Stat.event("mytrip", "mytrip_check_change", "2", 0);
				}
			}
		});

		mPager = (ViewPager) findViewById(R.id.vPager);

		initImageView();

		listViews = new ArrayList<View>();
		listViews.add(getLayoutInflater().inflate(R.layout.list_frame, null,
				false));
		listViews.add(getLayoutInflater().inflate(R.layout.list_frame, null,
				false));
		mPager.setAdapter(new MyPagerAdapter(listViews));
		mPager.setOnPageChangeListener(new MyOnPageChangeListener());
	}

	@Override
	public void onDestroy() {
		unregisterReceiver(receiver);
		super.onDestroy();
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setTitle(getResources().getString(R.string.tab_name_togo));

		initListView();
		IntentFilter filter = new IntentFilter(ACTION_TOGOLIST_CHANGED);
		registerReceiver(receiver, filter);
	}

	private void initImageView() {
		cursor = (ImageView) findViewById(R.id.cursor);
		bmpW = BitmapFactory.decodeResource(getResources(),
				R.drawable.page_cursor).getWidth();
		DisplayMetrics dm = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(dm);
		int screenW = dm.widthPixels;
		offset = (screenW / 2 - bmpW) / 2;
		Matrix matrix = new Matrix();
		matrix.postTranslate(offset, 0);
		cursor.setImageMatrix(matrix);
	}

	private void initListView() {
		adapter1 = new TodoAttractionListAdapter(0);
		adapter2 = new TodoAttractionListAdapter(1);

		if (listViews.size() == 2) {
			list1 = (ListView) listViews.get(0).findViewById(R.id.list);
			list1.setAdapter(adapter1);
			list1.setEmptyView(listViews.get(0).findViewById(R.id.empty));
			((TextView) (listViews.get(0).findViewById(R.id.text)))
					.setText(getString(R.string.togo_empty_msg));
			list1.setOnItemClickListener(this);
			list1.setOnItemLongClickListener(this);
			list1.setTag("list1");

			list2 = (ListView) listViews.get(1).findViewById(R.id.list);
			list2.setAdapter(adapter2);
			list2.setEmptyView(listViews.get(1).findViewById(R.id.empty));
			((TextView) (listViews.get(1).findViewById(R.id.text)))
					.setText(getString(R.string.togo_completed_empty_msg));
			list2.setOnItemClickListener(this);
			list2.setOnItemLongClickListener(this);
			list2.setTag("list2");
		}
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		if (currentLongClickItem != -1) {
			return;
		}

		TodoAttractionListAdapter adapter = currentAdapter(parent);
		Object item = adapter.getItem(position);
		if (!(item instanceof Attraction)) {
			return;
		}

		Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse("denny://tainfo"));
		i.putExtra("id", ((Attraction) item).getId());
		startActivity(i);

		Stat.event("mytrip", "mytrip_item_click", String.valueOf(position), 0);
	}

	private TodoAttractionListAdapter currentAdapter(AdapterView<?> parent) {
		TodoAttractionListAdapter adapter = null;
		if (parent.getTag() == list1.getTag()) {
			adapter = adapter1;
		} else if (parent.getTag() == list2.getTag()) {
			adapter = adapter2;
		}
		return adapter;
	}

	@Override
	public boolean onItemLongClick(final AdapterView<?> parent,
			final View view, final int position, final long id) {
		Stat.event("mytrip", "mytrip_item_longclick", String.valueOf(position),
				0);
		currentLongClickItem = position;

		mMode = startActionMode(new AnActionModeOfEpicProportions());

		return false;
	}

	private final class AnActionModeOfEpicProportions implements
			ActionMode.Callback {
		@Override
		public boolean onCreateActionMode(ActionMode mode, Menu menu) {

			if (currIndex == 0) {
				menu.add(getString(R.string.togo_menu_complete))
						.setIcon(R.drawable.ic_complete)
						.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
			}

			menu.add(getString(R.string.togo_menu_delete))
					.setIcon(R.drawable.ic_delete)
					.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);

			return true;
		}

		@Override
		public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
			return false;
		}

		@Override
		public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
			TogoDBHelper helper = TogoDBHelper.instance();
			if (getString(R.string.togo_menu_complete).equals(item.getTitle())) {
				Togo togo = adapter1.getTogo(currentLongClickItem);
				togo.setStatus(1);
				if (helper.update(togo) > 0) {
					Toast.makeText(
							MyCollectActivity.this,
							getResources().getString(
									R.string.message_update_success),
							Toast.LENGTH_SHORT).show();
					refresh();
				}

				Stat.event("mytrip", "mytrip_item_complete", null, 0);

			} else if (getString(R.string.togo_menu_delete).equals(
					item.getTitle())) {
				TodoAttractionListAdapter adapter = currIndex == 0 ? adapter1
						: adapter2;
				if (helper.delete(((Attraction) adapter
						.getItem(currentLongClickItem)).getId()) > 0) {
					Toast.makeText(
							MyCollectActivity.this,
							getResources().getString(
									R.string.message_delete_success),
							Toast.LENGTH_SHORT).show();
					refresh();
				}

				Stat.event("mytrip", "mytrip_item_delete", null, 0);
			}

			mode.finish();
			return true;
		}

		@Override
		public void onDestroyActionMode(ActionMode mode) {
			currentLongClickItem = -1;
		}
	}

	private void refresh() {
		adapter1.reset();
		adapter2.reset();
	}

	public class MyOnPageChangeListener implements OnPageChangeListener {

		int one = 0;
		int two = offset * 2 + bmpW;

		@Override
		public void onPageScrollStateChanged(int arg0) {
		}

		@Override
		public void onPageScrolled(int arg0, float arg1, int arg2) {
			if (mMode != null && currentLongClickItem != -1) {
				mMode.finish();
			}
		}

		@Override
		public void onPageSelected(int arg0) {
			Stat.event("mytrip", "mytrip_page_scroll", null, 0);

			Animation animation = null;
			switch (arg0) {
			case 0:
				if (currIndex == 1) {
					animation = new TranslateAnimation(two, one, 0, 0);
					group.check(R.id.btn_sort1);
				} else {
					return;
				}
				break;
			case 1:
				if (currIndex == 0) {
					animation = new TranslateAnimation(one, two, 0, 0);
					group.check(R.id.btn_sort2);
				} else {
					return;
				}
				break;
			}

			currIndex = arg0;
			animation.setFillAfter(true);// True:图片停在动画结束位置 　　
			animation.setDuration(300);
			cursor.startAnimation(animation);
		}
	}

	class TodoAttractionListAdapter extends BasicLoadAdapter<Attraction> {

		Map<Attraction, Togo> map;
		int type;

		public TodoAttractionListAdapter(int t) {
			type = t;
		}

		public void setData(Map<Attraction, Togo> m) {
			map = m;
			Set<Attraction> set = m.keySet();
			List<Attraction> attractionList = new ArrayList<Attraction>();
			for (Attraction attraction : set) {
				attractionList.add(attraction);
			}
			setData(attractionList);
		}

		public Togo getTogo(int position) {
			return map.get(getItem(position));
		}

		@Override
		public void reset() {
			if (map != null) {
				map.clear();
			}
			super.reset();
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			View view = super.getView(position, convertView, parent);
			if (view instanceof AttractionListItem) {
				Attraction ta = (Attraction) getItem(position);
				((AttractionListItem) view).setAttraction(ta);
			}
			return view;
		}

		@Override
		protected View itemViewForData(View convertView, ViewGroup parent) {
			if (convertView != null
					&& convertView instanceof AttractionListItem) {
				return convertView;
			}

			return LayoutInflater.from(parent.getContext()).inflate(
					R.layout.tourist_attraction_list_item, parent, false);
		}

		@Override
		public com.dennytech.tac.ui.adapter.BasicLoadAdapter.NetworkTask createTask() {
			Task task = new Task(this);
			task.type = this.type;
			return task;
		}

		@Override
		protected Attraction decodeObject(JSONObject object) {
			return Attraction.decode(object);
		}

	}

	class Task extends BasicLoadAdapter.NetworkTask {
		List<Togo> togoList;
		int type;

		public Task(BasicLoadAdapter<?> adapter) {
			super(adapter);
		}

		@Override
		protected AttractionListApi creatApi() {
			return new AttractionListApi();
		}

		@Override
		public JSONObject doInBackground(Integer... params) {
			if (togoList == null) {
				TogoDBHelper togoHelper = TogoDBHelper.instance();
				togoList = togoHelper.query(type);
			}

			if (togoList == null) {
				return null;
			}

			StringBuilder sb = new StringBuilder();
			for (int i = params[0]; i < togoList.size(); i++) {
				Togo togo = togoList.get(i);

				if (togo.getAttId() == 0) {
					continue;
				}

				if (i == togoList.size() - 1) {
					sb.append(togo.getAttId());
				} else {
					sb.append(togo.getAttId() + "s");
				}
			}

			((AttractionListApi) api).setIds(sb.toString());
			return ((AttractionListApi) api).query();
		}

		@Override
		public synchronized void onPostExecute(JSONObject result) {
			super.onPostExecute(result);
			if (result != null) {
				try {
					JSONArray array = result.getJSONArray("list");
					Map<Attraction, Togo> map = new HashMap<Attraction, Togo>();
					for (int i = 0; i < array.length(); i++) {
						Attraction attraction = Attraction.decode(array
								.getJSONObject(i));
						if (attraction != null) {
							map.put(attraction, togoList.get(i));
						}
					}
					((TodoAttractionListAdapter) adapter).setData(map);
				} catch (JSONException e) {
				}
			} else {

			}
		}

	}
}
